<?

class MAIL4 {
	function __construct( $type, $vars = false ){
		
		$this->type = $type;
		$this->done	= array();
		
		$this->modcon = new MOD_CONSTRUCT();
		if ($vars)
			$this->_addvars($vars);

		$this->update_db = false;
		
		if( !isset( $this->title )) $this->title = ACCOUNT;
		if( !isset($this->returnpath )) $this->returnpath = array( "news@" . engine_get( 'mail.ext' ) => engine_get( 'account' ) . " news"); 
	}
	
	function _addvars( $vars ){ foreach( $vars as $k=>$v ) if($k!=$this) $this->$k=$v; }
	
	function _parse_users( $get, $from, $where ){
		global $DB, $_init;
		
		$this->users = $DB->filter_key( "user_extend", $where, $get );
		//$this->users = $DB->parse($get,$from,$where,true);
	}
	
	function generate( $modid, $content ) {
		global $DB, $Engine;
		
		$this->_addvars( $this->modcon->request_json( $modid ));
		
		$replacevar = array(
			"%content%" => utf8_decode( $content )
		);
		
		$this->title = $Engine->text->get( $this->nameid );
		$this->html = $this->template_gen( $this->templateid, $replacevar );
	}
		
	function generate_newsletter( $letterid, $lang ) {
		global $DB, $Object, $Engine;
		
		// TEMP HOOK, SHOULD BE CHECKED!
		// ($Object will not always be present)  
		if( !$Object && !$letterid ) return false;

		$this->_addvars( $this->modcon->request_json( engine_get( "style:mod.letter.vars" )));
		$Page = new PAGE( $this->location );
		
		$side = array();
		if( $media = $Object->media->reference( "media.img" ))
			foreach ( $media as $el ) $side[] = "<img src='". engine_get( "url" ) ."/public.img?id=$el&sze={$this->imgsze}' />";
		
		$replacevar = array(
			"%date%"	=> date( "d.m Y", strtotime( $Object->get( "flog" ))),
			"%issue%"	=> $Object->id,
			"%year%"	=> $Object->get( "meta" )->year,
			"%url%"		=> $Page->url( "?letterid=". $Object->id ),
			"%style%"	=> PUBLIC_THEME . "/mailer",
			"%title%"	=> $this->title = utf8_decode( $Object->get( "name" )),
			"%side%"	=> implode( "\n", $side ),
			"%content%" => utf8_decode( $Object->get( "content" ))
		);
		
		if( $this->mods )
			$replacevar = array_merge( $replacevar, $this->filter_mods());

		$this->html = $this->template_gen( $this->html_template, $replacevar );
		
		$replacevar[ '%content%' ] = strip_tags( $replacevar[ '%content%' ]);
		$this->plain = $this->template_gen( $this->plain_template, $replacevar );
	}
	
	function template_gen( $textid, $replace ) {
		global $Engine;

		$template = $Engine->text->get( $textid, "long" );
		
		return wordwrap(
			str_replace( array_keys( $replace ), array_values( $replace ), $template )
		);
	}
	
	function send( $conditional = 0 ) {
		
		require_once ROOT . 'engine/ext/Swift/lib/swift_required.php';
		
		if( $this->users = $this->parseuser( $conditional )) {
		

#			Create the Mailer.
			$mailer = Swift_Mailer::newInstance( Swift_SmtpTransport::newInstance( 'localhost', 25 ));	

#			Create the message.
			$mail = Swift_Message::newInstance()
			
				->setSubject( $this->title )
				->setFrom( $this->returnpath )
				->setBody( $this->plain )
				->addPart( $this->html, "text/html" );
		
			
			foreach( $this->users as $ml ) {
					
				if( $ml['meta'] ) $ml = array_merge( $ml, json_decode( $ml['meta'], true ));
				$adress = ( $ml['mail'] )? $ml['mail'] : $ml['user'];
				
				if( strpos( $adress, "@" )) {
					$mail->addTo( $adress, $ml['fname']." ".$ml['lname'] );	
					
					$replace[ $adress ] = array('{email}'=>$adress, '{id}'=>$ml['ID']);
				}
				
				$this->done[] = $ml['ID'];
			}
			
			$mailer->registerPlugin( new Swift_Plugins_AntiFloodPlugin( 92, 24 ));
			$mailer->registerPlugin( new Swift_Plugins_ThrottlerPlugin( 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE ));
			$mailer->registerPlugin( new Swift_Plugins_DecoratorPlugin( $replace ));
		
			$numSent = 1;//$mailer->batchSend( $mail );
		
		} 
		
		return ( $numSent )? $this->done : array();
	}
	
	
	function parseuser( $id_or_where ) {
		global $DB;
		
		return $DB->filter_key( "user", $id_or_where, "user, ID, lang, meta" );
	}
	
	function filter_mods() {
		global $DB;
		
		$mods = array();
		foreach( $this->mods as $column => $ids )
			if( count( $ids )) foreach( $ids as $id ) {
			
				$Mod = $this->modcon->call(( int ) $id );
				$mods[ "%mods:$column%" ] .= $Mod->output();
			}
				
		return $mods;
	}

}


?>